//
//  ForgetPassViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/16.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

class ForgetPassViewController: BaseTableViewController {
    
    @IBOutlet weak var newPassWordField: UITextField!
    var type = 0 // 0忘记密码 1发送绑定设备的验证码
    @IBOutlet weak var confirmPassWordField: UITextField!
    
    var account = ""
    
    var password: String {
        get{
            return self.newPassWordField.text ?? ""
        }
        set{
            self.newPassWordField.text = newValue
        }
    }
    
    override var names: Array<String> {
        get{
            return ["code","authen","userinfo"]
        }
    }
    
    var timeRemaining: Int = 60
    
    @objc func updateTitle(timer: Timer)->Void{
        
        timeRemaining -= 1
        
        authenCodeBtn.setTitle(String(timeRemaining) + "s", for: .disabled)
        
        if timeRemaining == 0 {
            
            timer.invalidate()
            
            authenCodeBtn.isEnabled = true
        }
        
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func getCode(json: JSON)->Void{
            if let success = json.dictionary?["success"]?.rawValue as? Bool {
                if success == true {
                    self.timeRemaining = 60
                    authenCodeBtn.isEnabled = false
                    self.authenCodeBtn.setTitle(String(self.timeRemaining) + " s", for: .disabled)
                    Timer.scheduledTimer(timeInterval: TimeInterval(1.0), target: self, selector: #selector(updateTitle(timer:)), userInfo: nil, repeats: true)
                } else {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                }
            }
        }
        
        func suc(json: JSON)->Void{
            
            if json.contents?["success"] == true {
                
                self.navigationController?.popViewController(animated: true)
                
            } else {
                self.showError(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func userinfosuc(json: JSON){
            
            if let success = json.contents?["success"]?.rawValue as? Bool {
                if success == false {
                    return
                }
            }
            
            if let data = json.contents?["data"] {
                
                if let nm = data.contents?["name"]?.rawString() {
                    User.configName(name: nm)
                }
                
                if let account = data.contents?["account"]?.rawString() {
                    User.configAccount(account: account)
                }
                
                if let id = data.contents?["id"]?.rawString() {
                    User.configId(id: id)
                }
                
                if let phe = data.contents?["phone"]?.rawString() {
                    User.configPhone(phone: phe)
                }
                if let code = data.contents?["orgCode"]?.rawString() {
                    User.configOrgCode(orgCode: code)
                }
                
                if let admin = data.contents?["admin"]?.int {
                    if admin == 1 {
                        User.configIfAdmin(ifadmin: true)
                    } else {
                        User.configIfAdmin(ifadmin: false)
                    }
                } else {
                    User.configIfAdmin(ifadmin: false)
                }
                NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: "UserInfoReady")))
                
                JPUSHService.setAlias(User.id, completion: { (code, str, code1) in
                    
                }, seq: 1)
                
                let animation = CATransition.init()
                
                animation.type = CATransitionType.fade
                
                UIApplication.shared.delegate?.window??.layer.add(animation, forKey: nil)
                
                let story = UIStoryboard(name: "Main", bundle: Bundle.main)
                
                let rootVC = story.instantiateInitialViewController()
                
                UIApplication.shared.delegate?.window??.rootViewController = rootVC
                
            }
        }
        switch name {
        case "code":
            return getCode
        case "userinfo":
            return userinfosuc
        default:
            return suc
        }
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        switch name {
        case "code":
            return ["phone": (self.phoneNumberField.text ?? "")]
        case "userinfo":
            return [:]
        default:
            return ["phone": self.phoneNumberField.text!,"password": (self.newPassWordField.text ?? ""),"confirmPwd": (self.confirmPassWordField.text ?? ""),"verificationCode": Int(self.codeField.text!) ?? 0]
        }
    }
    
    override func path(for name: String) -> String{
        if name == "code" {
            return ForgetPassGetCode
        } else if name == "authen" {
            return ForgetPass
        } else {
            return GetUserInfo
        }
    }
    
    override func method(for name: String) -> NetMethod{
        if name == "code" || name == "userinfo" {
            return .get
        }
        return .post
    }
    
    //响应接口的有效性策略,如果参数不合格，则默认根据String提示
    override func strategy(for name: String) -> (Bool,String?,(()->Void)?) {
        
        if name == "code" {
            
            if self.phoneNumberField.text?.isPhone != true {
                
                return (false,"请输入正确的手机号",nil)
                
            }
            
        }
        
        if name == "authen" {
            
            
            if self.phoneNumberField.text?.count == 0 {
                return (false,"无手机号!",nil)
            }
            if self.codeField.text?.count == 0 {
                return (false,"验证码为空",nil)
            }
            if newPassWordField.text?.count == 0 {
                return (false,"请输入新的密码",nil)
            }
            if confirmPassWordField.text?.count == 0 {
                return (false,"请输入验证密码",nil)
            }
            if confirmPassWordField.text != newPassWordField.text {
                return (false,"请保证密码一致!",nil)
            }
            return (true,nil,nil)
        }
        
        return (true,nil,nil)
        
    }
    
    
    @IBOutlet weak var authenCodeBtn: UIButton!
    
    
    @IBOutlet weak var phoneNumberField: UITextField!
    
    
    @IBOutlet weak var codeField: UITextField!
    
    
    @IBAction func getCodeAction(_ sender: Any) {
        self.load(with: "code")
    }
    
    @IBAction func nextStepAction(_ sender: Any) {
        self.view.endEditing(true)
        self.load(with: "authen")
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.navigationItem.hidesBackButton = true
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "icon_nav_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(pop))
        self.navigationItem.leftBarButtonItem?.tintColor = UIColor.hex("333333")
        authenCodeBtn.setTitleColor(UIColor.red, for: .disabled)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}
